/*
 * Copyright (C) 2013 'Chaos'.Personal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.silly.adapter.entity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.util.Pair;
import android.util.SparseIntArray;

import com.silly.adapter.annotation.SillyField;
import com.silly.adapter.annotation.SillyLayoutId;
import com.silly.adapter.entity.EntityItem.EntityItemBuilder;
import com.silly.adapter.reflect.ReflectUtils;

/**
 * 抓取所有Object中的可用信息，交付给{@link EntityItem}
 * 
 * @author Chaos
 * @date 2013-8-6
 */
public class EntityGrub {
    
	private List<Integer> mTypeSet = null;
	
	private SparseIntArray mTypeRelation = null;
	
	private int mPos = 0;
	
	public int getTypeCount(){
		return mTypeSet.size();
	}

	public int getType(int pos){
		return mTypeRelation.get(pos);
	}
    
	public Object grubField(Object bean,String field){
		return ReflectUtils.getValue(bean, field);
	}
    
	public EntityItem grub(SillyBean obj) {
		SillyLayoutId layout = ReflectUtils.getAnnotation(SillyLayoutId.class, obj);
		if (layout == null || layout.id() == 0) {
			// check error
			throw new RuntimeException("the layoutId is not set");
		}
		
		if(!mTypeSet.contains(layout.id())){
            mTypeSet.add(layout.id());
		}
		
		mTypeRelation.put(mPos, mTypeSet.indexOf(layout.id()));
		mPos++;

		// create builder to build EntityItem
		EntityItemBuilder builder = new EntityItemBuilder();
		// put layoutId...
		builder.put(layout.id());

		Field[] fields = obj.getClass().getDeclaredFields();
		for (Field field : fields) {
			// traversal
			SillyField aField = ReflectUtils.getAnnotation(SillyField.class, obj, field);
			if (aField == null || aField.id() == 0) {
				throw new RuntimeException("the fieldId is not set");
			}

			Pair<Object, DataType> value = new Pair<Object, DataType>(ReflectUtils.getValue(obj, field), aField.type());
			builder.put(aField.id(), value);
		}

		return builder.build();
	}

	public List<EntityItem> grubList(List<SillyBean> objs) {
        
		//init type set
		mTypeSet = new ArrayList<Integer>(objs.size());
		//init Type Relation
		mTypeRelation = new SparseIntArray(objs.size());
		
		List<EntityItem> resultList = new ArrayList<EntityItem>();

		// traversal
		for (SillyBean sb : objs) {
            resultList.add(grub(sb));
		}
		return resultList;
	}

}
